<?php

if (!defined('ROOT'))
    die();

class Adminarea_mods {

    private $addonsAll = array();
    private $addonsInstalled = array();
    private $addonsNotInstalled = array();

    public function recount() {
	for ($i = 0, $n = count($addons); $i < $n; $i++) {
	    $type = $addons[$i]['type'];
	    $name = $addons[$i]['name'];

	    switch ($type) {
		case 'module':
		    if (!is_dir(MAINDIR . '/modules/' . $name . '/')) {
			Mysql::getInstance()->delete('modules', "type='module' AND name='$name'");
		    }
		    break;
		case 'editor':
		    if (!is_dir(MAINDIR . '/editors/' . $name . '/')) {
			Mysql::getInstance()->delete('modules', "type='editor' AND name='$name'");
		    }
		    break;
		case 'plugin':
		    if (!file_exists(MAINDIR . '/plugins/' . $name)) {
			Mysql::getInstance()->delete('modules', "type='plugin' AND name='$name'");
		    }
		    break;
	    }
	}

	$arr = Mysql::getInstance()->select('modules');
	$set = array();
	Mysql::getInstance()->delete('modules');
	foreach ($arr as $a) {
	    if (!isset($set[$a['type']][$a['name']])) {
		$set[$a['type']][$a['name']] = true;
		if (($a['type'] == '') || ($a['name'] == ''))
		    continue;
		Mysql::getInstance()->insert('modules', array('type' => $a['type'], 'name' => $a['name']));
	    }
	}

	Cache::clear();
	Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Дані про додатки оновлено')));
    }

    public function init() {

	$addons = Mysql::getInstance()->select('modules');

	if (isset($_GET['action']) && $_GET['action'] == 'recount') {
	    $this->recount();
	} else {
	    foreach ($addons as $addon) {
		switch ($addon['type']) {
		    case 'module':
			$this->addonsInstalled['modules'][] = $addon['name'];
			break;
		    case 'editor':
			$this->addonsInstalled['editors'][] = $addon['name'];
			break;
		    case 'plugin':
			$this->addonsInstalled['plugins'][] = $addon['name'];
			break;
		}
	    }
	    //All plugins
	    $this->addonsAll['plugins'] = read_directory(MAINDIR . '/plugins/', 0, 1, 'php');
	    $this->addonsAll['editors'] = read_directory(MAINDIR . '/editors/', 1, 0);
	    $this->addonsAll['modules'] = read_directory(MAINDIR . '/modules/', 1, 0);


	    //not installed plugins
	    $this->addonsNotInstalled['plugins'] = array_diff($this->addonsAll['plugins'], $this->addonsInstalled['plugins']);
	    $this->addonsNotInstalled['plugins'] = array_values($this->addonsNotInstalled['plugins']);

	    $this->addonsNotInstalled['editors'] = array_diff($this->addonsAll['editors'], $this->addonsInstalled['editors']);
	    $this->addonsNotInstalled['editors'] = array_values($this->addonsNotInstalled['editors']);

	    $this->addonsNotInstalled['modules'] = array_diff($this->addonsAll['modules'], $this->addonsInstalled['modules']);
	    $this->addonsNotInstalled['modules'] = array_values($this->addonsNotInstalled['modules']);

	    if (isset($_GET['manage'])) {
		$manage = $_GET['manage'];
	    } elseif (isset($_GET['deactivate'])) {
		$manage = $_GET['deactivate'];
	    } elseif (isset($_GET['activate'])) {
		$manage = $_GET['activate'];
	    } else {
		$manage = '';
	    }
	    switch ($manage) {
		case 'modules':
		    $this->manageModule();
		    break;
		case 'plugins':
		    $this->managePlugin();
		    break;
		case 'editors':
		    $this->manageEditor();
		    break;
		default:
		    $this->getAllList();
		    break;
	    }
	}
    }

    private function getAllList() {
	Aurus::getInstance()->addContent(
		Html::table(
			Html::tr(Html::td(' ', 'chead', 'left', '40%') .
				Html::td(__('Загальна кількість'), 'chead', 'left', '20%') .
				Html::td(__('Активовано'), 'chead', 'left', '20%') .
				Html::td(__('Не активовано'), 'chead', 'left', '20%')
			) .
			Html::tr(Html::td(Html::tag(__('Модулі'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=modules')), 'confclass', 'left', '40%') .
				Html::td(count($this->addonsAll['modules']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsInstalled['modules']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsNotInstalled['modules']), 'confclass', 'left', '20%')
			) .
			Html::tr(Html::td(Html::tag(__('Плаґіни'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugins')), 'confclass', 'left', '40%') .
				Html::td(count($this->addonsAll['plugins']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsInstalled['plugins']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsNotInstalled['plugins']), 'confclass', 'left', '20%')
			) .
			Html::tr(Html::td(Html::tag(__('Редактори'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=editors')), 'confclass', 'left', '40%') .
				Html::td(count($this->addonsAll['editors']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsInstalled['editors']), 'confclass', 'left', '20%') .
				Html::td(count($this->addonsNotInstalled['editors']), 'confclass', 'left', '20%')
			)
		)
	);

	Aurus::getInstance()->addContent('<br /><a href="' . LINK_ROOT . 'adminarea/?do=mods&amp;action=recount">' . __('Оновити дані про додатки') . '</a>');
    }

    private function manageEditor() {

	if (isset($_GET['manage'])) {

	    $index = $_GET['manage'];
	    $table = Html::tr(
			    Html::td(__('Назва'), 'chead', 'left', '34%') .
			    Html::td(__('Статус'), 'chead', 'left', '33%') .
			    Html::td(__('Дія'), 'chead', 'left', '33%')
	    );
	    for ($i = 0, $n = count($this->addonsInstalled[$index]); $i < $n; $i++) {
		$addn = $this->addonsInstalled[$index][$i];
		$addn = $addn;
		$table .= Html::tr(
				Html::td($addn, 'confclass', 'left', '34%') .
				Html::td(Html::tag(__('Додаток увімкнений'), 'span', array('style' => 'color:green')), 'confclass', 'left', '33%') .
				Html::td(Html::tag(__('Вимкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;deactivate=' . $index . '&amp;name=' . $addn)), 'confclass', 'left', '33%'));
	    }

	    for ($i = 0, $n = count($this->addonsNotInstalled[$index]); $i < $n; $i++) {
		$addn = $this->addonsNotInstalled[$index][$i];
		$addn = ($index == 'plugins') ? substr($addn, 0, -4) : $addn;
		$table .= Html::tr(Html::td($addn, 'confclass', 'left', '34%') . Html::td(Html::tag(__('Додаток вимкнений'), 'span',
						array('style' => 'color:red')), 'confclass', 'left', '33%') . Html::td(Html::tag(__('Увімкнути'), 'a', array('href' =>
					    LINK_ROOT . 'adminarea/?do=mods&amp;activate=' . $index . '&amp;name=' . $addn)), 'confclass', 'left', '33%'));
	    }
	    Aurus::getInstance()->addContent(Html::table($table));
	} elseif (isset($_GET['activate'])) {
	    $type = substr($_GET['activate'], 0, -1);
	    Mysql::getInstance()->insert('modules', array('type' => $type, 'name' => $_GET['name']));

	    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток увімкнено')));
	    Cache::clear();
	} elseif (isset($_GET['deactivate'])) {
	    $type = substr($_GET['deactivate'], 0, -1);
	    Mysql::getInstance()->delete('modules', "type='{$type}' AND name='{$_GET['name']}'");
	    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток вимкнено')));
	    Cache::clear();
	}
    }

    private function manageModule() {

	if (isset($_GET['manage'])) {
	    $index = 'modules';

	    $table = Html::tr(Html::td(__('Назва'), 'chead', 'left', '9%') . Html::td(__('Версія'), 'chead', 'left', '2%') . Html::td(__('Автор'), 'chead', 'left', '9%') . Html::td(__('Опис'), 'chead', 'left', '60%') . Html::td(__('Статус'), 'chead', 'left', '10%') . Html::td(__('Дія'), 'chead', 'left', '10%'));
	    foreach ($this->addonsInstalled[$index] as $addn) {
		if ($addn == 'users' or $addn == 'captcha') {
		    $disable = '';
		} else {
		    $disable = Html::tag(__('Вимкнути'), 'a', array('onclick' => 'return confirm(\'' . __('Ви впевнені що хочете вимкнути модуль? Всі дані буде втрачено!') . '\');', 'href' => LINK_ROOT . 'adminarea/?do=mods&amp;deactivate=' . $index . '&amp;name=' . $addn));
		}
		if (is_file(MAINDIR . '/modules/' . $addn . '/info.xml')) {
		    $nfo = simplexml_load_file(MAINDIR . '/modules/' . $addn . '/info.xml');
		}
		$name = $addn;
		if (isset($nfo)) {
		    $name = $nfo->name;
		    if ($nfo->module_url) {
			$name = Html::tag($name, 'a', array('href' => $nfo->module_url));
		    }
		}
		$author = '';
		if (isset($nfo)) {
		    $author = $nfo->author;
		    if ($nfo->author_url) {
			$author = Html::tag($author, 'a', array('href' => $nfo->author_url));
		    }
		}

		$table .=
			Html::tr(Html::tag($name, 'td', array('class' => 'confclass')) .
				Html::tag(isset($nfo) ? $nfo->version : '', 'td', array('class' => 'confclass')) .
				Html::tag($author, 'td', array('class' => 'confclass')) .
				Html::tag(isset($nfo) ? $nfo->description : '', 'td', array('class' => 'confclass')) .
				Html::tag(Html::tag(__('Модуль увімкнений'), 'span', array('style' => 'color:green')), 'td', array('class' => 'confclass')) .
				Html::td($disable, 'confclass', 'left', '33%'));
		unset($nfo);
	    }
	    foreach ($this->addonsNotInstalled[$index] as $addn) {
		if (is_file(MAINDIR . '/modules/' . $addn . '/info.xml')) {
		    $nfo = simplexml_load_file(MAINDIR . '/modules/' . $addn . '/info.xml');
		}
		$name = $addn;
		if (isset($nfo)) {
		    $name = $nfo->name;
		    if ($nfo->module_url) {
			$name = Html::tag($name, 'a', array('href' => $nfo->module_url));
		    }
		}
		$author = '';
		if (isset($nfo)) {
		    $author = $nfo->author;
		    if ($nfo->author_url) {
			$author = Html::tag($author, 'a', array('href' => $nfo->author_url));
		    }
		}
		$table .= Html::tr(
		Html::tag($name, 'td', array('class' => 'confclass')) .
		Html::tag(isset($nfo) ? $nfo->version : '', 'td', array('class' => 'confclass')) .
		Html::tag($author, 'td', array('class' => 'confclass')) .
		Html::tag(isset($nfo) ? $nfo->description : '', 'td', array('class' => 'confclass')) .
		Html::tag(Html::tag(__('Модуль вимкнено'), 'span', array('style' => 'color:red')), 'td', array('class' => 'confclass')) .
		Html::tag(
		    Html::tag(__('Увімкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;activate=' . $index . '&amp;name=' . $addn)) . ' | ' .
		    Html::tag(__('Експорт'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;export=' . $addn))
		, 'td', array('class' => 'confclass', 'align' => 'left', 'width' => '33%'))
		);
		unset($nfo);
	    }
	    // .
//						

	    Aurus::getInstance()->addContent(Html::table($table));
	} elseif (isset($_GET['activate'])) {
	    $type = substr($_GET['activate'], 0, -1);

	    $module = 'Module_' . $_GET['name'];
	    Factory::get($module)->onActivate();

	    Mysql::getInstance()->insert('modules', array('type' => $type, 'name' => $_GET['name']));
	    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток увімкнено')));
	    Cache::clear();
	} elseif (isset($_GET['deactivate'])) {
	    $module = 'Module_' . $_GET['name'];
	    Factory::get($module)->onDeactivate();

	    $type = substr($_GET['deactivate'], 0, -1);
	    Mysql::getInstance()->delete('modules', "type='{$type}' AND name='{$_GET['name']}'");
	    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток вимкнено')));
	    Cache::clear();
	} elseif (isset($_GET['export'])) {
	    
	}
    }

    private function managePlugin() {

	if (isset($_GET['manage_plugin'])) {
	    $p_class = 'Plugin_' . $_GET['manage_plugin'];

	    if (class_exists($p_class) && Aurus::getInstance()->is_plugin($p_class)) {
		if (Factory::runStatic($p_class, 'getHasAdmin')) {
		    Factory::runStatic($p_class, 'initAdminArea');
		    if (!Aurus::getInstance()->getContent()) {
			Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Настройки недоступні')));
		    }
		} else {
		    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Настройки недоступні')));
		}
	    } else {
		Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Такого плагіну нема')));
	    }
	} elseif (isset($_GET['manage'])) {
	    $index = 'plugins';
	    $table = Html::tr(
			    Html::td(__('Назва'), 'chead', 'left', '16%') .
			    Html::td(__('Версія'), 'chead', 'left', '16%') .
			    Html::td(__('Опис'), 'chead', 'left', '48%') .
			    Html::td(__('Статус'), 'chead', 'left', '10%') .
			    Html::td(__('Дія'), 'chead', 'center', '10%', 'top', '2'));

	    for ($i = 0, $n = count($this->addonsInstalled[$index]); $i < $n; $i++) {
		$addn = $this->addonsInstalled[$index][$i];
		$addn = substr($addn, 0, -4);
		$pName = 'Plugin_' . $addn;
		if (!class_exists($pName))
		    continue;
		if (Factory::runStatic($pName, 'getHasAdmin')) {
		    $settings = '<a href="' . LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugins&amp;manage_plugin=' . $addn . '">' . __('Налаштувати') . '</a>';
		} else {
		    $settings = '<span class="inactive">' . __('Налаштувати') . '</span>';
		}
		$table .= Html::tr(
				Html::td(Factory::runStatic($pName, 'getName'), 'confclass', 'left', '16%') .
				Html::td(Factory::runStatic($pName, 'getVersion'), 'confclass', 'left', '16%') .
				Html::td(Factory::runStatic($pName, 'getDescription'), 'confclass', 'left', '48%') .
				Html::td(Html::tag(__('Додаток увімкнений'), 'span', array('style' => 'color:green')), 'confclass', 'left', '10%') .
				Html::td($settings, 'confclass', 'left', '5%') .
				Html::td(Html::tag(__('Вимкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;deactivate=' . $index . '&amp;name=' . $addn)), 'confclass', 'left', '5%')
		);
	    }

	    for ($i = 0, $n = count($this->addonsNotInstalled[$index]); $i < $n; $i++) {
		$addn = $this->addonsNotInstalled[$index][$i];

		$addn = substr($addn, 0, -4);
		$pName = 'Plugin_' . $addn;
		if (!class_exists($pName))
		    continue;

		$table .= Html::tr(
				Html::td(Factory::runStatic($pName, 'getName'), 'confclass', 'left', '16%') .
				Html::td(Factory::runStatic($pName, 'getVersion'), 'confclass', 'left', '16%') .
				Html::td(Factory::runStatic($pName, 'getDescription'), 'confclass', 'left', '48%') .
				Html::td(Html::tag(__('Додаток вимкнений'), 'span', array('style' => 'color:red')), 'confclass', 'left', '10%') .
				Html::td('<span class="inactive">' . __('Налаштувати') . '</span>', 'confclass', 'left', '5%') .
				Html::td(Html::tag(__('Увімкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;activate=' . $index . '&amp;name=' . $addn)), 'confclass', 'left', '5%')
		);
	    }

	    Aurus::getInstance()->addContent(Html::table($table));
	} elseif (isset($_GET['activate'])) {
	    $type = 'plugin';
	    $pluginClass = 'Plugin_' . $_GET['name'];
	    if (Aurus::getInstance()->is_plugin($pluginClass)) {
		$_GET['name'] = $_GET['name'] . '.php';
		Mysql::getInstance()->insert('modules', array('type' => $type, 'name' => $_GET['name']));
		Factory::runStatic($pluginClass, 'onActivate');
		Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток увімкнено')));
		Cache::clear();
	    } else {
		Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток не може бути увімкнений. Клас плагіну не реалізує інтерейс \'Plugin\'')));
	    }
	} elseif (isset($_GET['deactivate'])) {
	    $pluginClass = 'Plugin_' . $_GET['name'];
	    Factory::runStatic($pluginClass, 'onDeactivate');
	    $type = 'plugin';
	    $_GET['name'] = $_GET['name'] . '.php';
	    Mysql::getInstance()->delete('modules', "type='{$type}' AND name='{$_GET['name']}'");
	    Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток вимкнено')));
	    Cache::clear();
	}
    }



}